package com.boyuan.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JWTUtils {
    //    token 加密时候 使用的密钥 一旦得到密钥 也就可以来伪造token
    public final static String secretKey = "boyuan@blog";
    // token的有效时间
    public final static long keepTime = 1800000;
    /**JWT的Token的组成
     * Head  使用base64 进行编码之后得到信息
     * 载荷 Payload 一般是用户信息和声明
     * 签证Signature 一般密钥和签名
     *id 用户id
     * issuer 签发这
     * subject 用户名
     */
    public static String generalToken(String id,String issue,String subject){
        long ttMills = keepTime;
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMills = System.currentTimeMillis();
        Date now = new Date(nowMills);
        byte[] apiKeySecretBytes =  DatatypeConverter.parseBase64Binary(secretKey);
        Key signKey = new SecretKeySpec(apiKeySecretBytes,signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now);
        if (subject!=null){
            builder.setSubject(subject);
        }
        if (issue!=null){
            builder.setIssuer(issue);
        }
        builder.signWith(signatureAlgorithm,signKey);
        if (ttMills>=0){
            long expMills = nowMills+ttMills;
            Date exp = new Date(expMills);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }
    public static String updateToken(String token){
        Claims claims = verifyToken(token);
        String id = claims.getId();
        String issue = claims.getIssuer();
        String subject = claims.getSubject();
        return generalToken(id,issue,subject);
    }
    private static Claims verifyToken(String token){
        Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(secretKey)).parseClaimsJws(token).getBody();
        return claims;
    }
}
